const Redis = require('ioredis');
const { Sequelize } = require('sequelize');
const config = require('./config/config.json').development;

// Redis连接配置
const redis = new Redis({
  port: 6379,
  host: '127.0.0.1',
  db: 0,
});

// 数据库连接配置
const sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  dialect: config.dialect,
  port: config.port,
});

async function checkSalesOrderData() {
  try {
    console.log('开始检查Redis中的销售订单数据...');
    
    // 获取所有相关的keys
    const keys = await redis.keys('plugin_data_batch:*');
    console.log(`找到 ${keys.length} 个批次数据`);
    
    let salesOrderKeys = [];
    
    // 检查所有批次，找出sales_order类型的数据
    for (const key of keys) {
      const dataStr = await redis.get(key);
      
      if (!dataStr) {
        continue;
      }
      
      try {
        const data = JSON.parse(dataStr);
        // 检查是否为销售订单数据
        if (Array.isArray(data) && data.length > 0) {
          const firstItem = data[0];
          if (firstItem && firstItem.url && firstItem.url.includes('order') || firstItem.url.includes('订单')) {
            salesOrderKeys.push({key, data});
          }
        }
      } catch (parseError) {
        // 忽略解析错误
      }
    }
    
    console.log(`找到 ${salesOrderKeys.length} 个可能的销售订单批次`);
    
    // 显示销售订单数据的详细信息
    for (const {key, data} of salesOrderKeys) {
      console.log(`\n检查销售订单批次: ${key}`);
      console.log(`  数据条数: ${data.length}`);
      if (data.length > 0) {
        console.log('  第一条数据预览:');
        console.log(JSON.stringify(data[0], null, 2));
      }
    }
    
    // 检查数据库中的最新sales_order批次记录
    console.log('\n检查数据库中的sales_order批次记录...');
    const [batchResults] = await sequelize.query(
      'SELECT batch_id, data_type, status, created_at FROM plugin_data_batches WHERE data_type = "sales_order" ORDER BY created_at DESC LIMIT 10'
    );
    
    batchResults.forEach(batch => {
      console.log(`- 批次ID: ${batch.batch_id}, 类型: ${batch.data_type}, 状态: ${batch.status}, 创建时间: ${batch.created_at}`);
    });
    
    // 检查最近的批次数据内容
    if (batchResults.length > 0) {
      console.log('\n检查最近的sales_order批次数据内容...');
      for (const batch of batchResults.slice(0, 3)) {
        const key = `plugin_data_batch:${batch.batch_id}`;
        const dataStr = await redis.get(key);
        
        if (dataStr) {
          try {
            const data = JSON.parse(dataStr);
            console.log(`\n批次 ${batch.batch_id} 数据:`);
            console.log(`  数据类型: ${data.type || '未知'}`);
            console.log(`  数据条数: ${Array.isArray(data) ? data.length : '非数组格式'}`);
            
            if (Array.isArray(data) && data.length > 0) {
              console.log('  第一条数据预览:');
              console.log(JSON.stringify(data[0], null, 2));
            }
          } catch (parseError) {
            console.log(`  数据解析失败: ${parseError.message}`);
          }
        } else {
          console.log(`  批次 ${batch.batch_id} 数据不存在或已过期`);
        }
      }
    }
    
  } catch (error) {
    console.error('检查销售订单数据时出错:', error);
  } finally {
    await redis.quit();
    await sequelize.close();
  }
}

checkSalesOrderData();